﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Icoders.MarketTracker.Core.MasterData;
using Icoders.MarketTracker.Core.Repository.MasterDataRepositories;
using Icoders.MarketTracker.Core.Validation;
using Icoders.MarketTracker.Data.EF;
using Icoders.MarketTracker.Data.Utils;

namespace Icoders.MarketTracker.Data.Repository.MasterDataRepositories
{
    public class ApplicationRepository :RepositoryBase, IApplicationRepository
    {
        private AppDataContext _ctx;

        public ApplicationRepository(AppDataContext ctx)
       {
           _ctx = ctx;
           
       }
        public ValidationResultInfo Validate(MApplication objToValidate)
        {
            ValidationResultInfo vri = objToValidate.BasicValidation();
            
            return vri;
        }

        public int Save(MApplication entity)
        {
            ValidationResultInfo vri = Validate(entity);
            if (!vri.IsValid)
            {
                throw new DomainValidationException(vri, "Area Details provided not Valid");
            }
            DateTime date = TimeUtil.GetDateTime();
            TblApplication tbl = _ctx.TblApplication.FirstOrDefault(s => s.Id == entity.Id);
            if (tbl == null)
            {
                tbl = new TblApplication();
                tbl.CreatedOn = date;
                tbl.StatusId = (int)MasterEntityStatus.New;
                _ctx.TblApplication.AddObject(tbl);
               
            }
            tbl.UpdatedOn = date;
            tbl.UserId = entity.UserId;
            _ctx.SaveChanges();
            
            return tbl.Id;
        }

        public MApplication GetById(int id)
        {
            var tbl = _ctx.TblApplication.FirstOrDefault(s => s.Id == id);
            if (tbl == null) return null;
            return Map(tbl);
        }

        private MApplication Map(TblApplication tbl)
        {
            return new MApplication()
            {
                Id = tbl.Id,
                UserId = tbl.UserId,
                UpdatedOn = tbl.UpdatedOn,
                CreatedOn = tbl.CreatedOn,
                Status = (MasterEntityStatus)tbl.StatusId

            };
        }

        public List<MApplication> GetAll()
        {
            return _ctx.TblApplication.ToList().Select(n => Map(n)).ToList();
        }

        public void Delete(int id)
        {
            throw new NotImplementedException();
        }

        protected override string _cacheKey
        {
            get { throw new NotImplementedException(); }
        }

        protected override string _cacheListKey
        {
            get { throw new NotImplementedException(); }
        }
    }
}
